    //
    //  EJSGoodsListViewController.m
    //  EnjoyShoppingStreet
    //
    //  Created by lifayu on 2017/12/25.
    //  Copyright © 2017年 lifayu. All rights reserved.
    //

#import "EJSGoodsListViewController.h"
#import "EJSGoodsDetailInfoViewController.h"

#import "EJSSegmentedControl.h"
#import "EJSGoodsCCell.h"
#import "EJSSearchGoodsRequest.h"
#import "EJSGoodsListRequest.h"
#import "EJSCategoryModel.h"
#import "XOPlatformCategoryModel.h"
#import "EJSGoodsDetailInfoRequest.h"
#import "EJSGoodsAddCartRequest.h"
#import "EJSSelectGoodsSpecView.h"
#import "EJSHomeGoodCollectionViewCell.h"
#import "EJSShoppingCartListRequest.h"
#import "XOShopViewModel.h"
#import "XOGoodsCartListView.h"
#import "XOShoppingCartListRequest.h"
#import "XOShoppingCartModel.h"
#import "XOShoppingCartListModel.h"

@interface EJSGoodsListViewController ()<EJSSegmentedControlDelegate, EJSHomeGoodCollectionViewCellDelegate, XOSHoppingCartViewProtocol, UICollectionViewDelegate, UICollectionViewDataSource>{
    UIButton *_currentSelectButton;
    NSString *_order;//onsaleDesc上架时间逆序  onsaleAsc上架时间顺序 priceAsc价格顺序 priceDesc价格逆序
    NSString *_categoryId;//子分类当前选择的id
    NSString *_sortId;//平台子分类当前选择的id
    NSInteger _currentPage;
}
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet EJSSegmentedControl *segmentedControl;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *segmentedControlHeight;


@property (weak, nonatomic) IBOutlet UIButton *defaultButton;
@property (weak, nonatomic) IBOutlet UIButton *salesButton;
@property (weak, nonatomic) IBOutlet UIButton *priceButton;
@property (weak, nonatomic) IBOutlet UIImageView *priceAscImageView;
@property (weak, nonatomic) IBOutlet UIImageView *priceDescImageView;
@property (weak, nonatomic) IBOutlet UIButton *onSaleButton;
@property (weak, nonatomic) IBOutlet UIImageView *onSaleTimeAscImageView;
@property (weak, nonatomic) IBOutlet UIImageView *onSaleDescImageView;

@property (strong, nonatomic) NSMutableArray *goodsList;
@property (strong, nonatomic) EJSGoodsSkuModel *selectSkuModel;
@property (strong, nonatomic) XOShoppingCartListModel *shoppingCartListModel;
@property (strong, nonatomic) XOShoppingCartModel *shopCartModel;
StrongProperty XOPlatformCategoryModel *previousCategoryModel;
AssignProperty BOOL canWriteIndex;
AssignProperty BOOL hasPlatform;
@end

@implementation EJSGoodsListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
        // Do any additional setup after loading the view from its nib.
    self.collectionView.scrollsToTop = YES;

    [self filterActin:self.defaultButton];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
}

- (void)configOwnViews{
    if(_keyWord) {
        self.title = _keyWord;
        _segmentedControlHeight.constant = 0;
    }
    
    if (_singleCategoryModel) {
        self.title = _singleCategoryModel.categoryName;
        _categoryId = _singleCategoryModel.categoryId;
        _segmentedControlHeight.constant = 0;
    }
    
    if(_categoryModel) {
        self.title = _categoryModel.categoryName;
        if(_categoryModel.sons.count == 0) {
            _segmentedControlHeight.constant = 0;
        }else {
            NSMutableArray *categoryTitles = [NSMutableArray array];
            [categoryTitles addObject:@"全部"];
            for (int index = 0; index < _categoryModel.sons.count; index ++) {
                EJSCategoryModel *category = _categoryModel.sons[index];
                [categoryTitles addObject:category.categoryName?category.categoryName:@""];
            }
            [self.segmentedControl setCategoryTitles:categoryTitles];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.segmentedControl.selectedIndex = self.selectCategoryIndex+1;
            });
        }
        if(self.selectCategoryModel){
            _categoryId = self.selectCategoryModel.categoryId;
        }else {
            _categoryId = _categoryModel.categoryId;
        }
    }
    
    if(_platformCategoryModel){
        self.title = _platformCategoryModel.sortName;
        if(_platformCategoryModel.sons.count == 0){
            self.hasPlatform = NO;
            _segmentedControlHeight.constant = 0;
        }else{
            self.hasPlatform = YES;
            NSMutableArray *categoryTitles = [NSMutableArray array];
            [categoryTitles addObject:@"全部"];
            for (int index = 0; index < _platformCategoryModel.sons.count; index ++)
              {
                XOPlatformCategoryModel *category = _platformCategoryModel.sons[index];

                [categoryTitles addObject:category.sortName?category.sortName:@""];
              }
            [self.segmentedControl setCategoryTitles:categoryTitles];
            self.segmentedControl.selectedIndex = 0;
            self.previousCategoryModel = _platformCategoryModel;
            self.previousCategoryModel.memorySroll = YES;
            self.canWriteIndex = NO;
        }
        _sortId = _platformCategoryModel.sortId;
    }
    self.segmentedControl.delegate = self;
    self.segmentedControl.clipsToBounds = YES;
    [self.collectionView registerNib:[UINib nibWithNibName:@"EJSHomeGoodCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"EJSHomeGoodCollectionViewCell"];
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _currentPage = 1;
        [self getGoodsList];
    }];
    self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _currentPage ++;
        [self getGoodsList];
    }];
    self.collectionView.mj_footer.automaticallyHidden = YES;
}


- (void)resetRequestData{
    _categoryId = _categoryModel.categoryId;
    _sortId = _platformCategoryModel.sortId;
    _order = nil;
    _currentPage = 1;
    [self updatePriceOrderImageView];
    [self updateOnSaleTimeOrderImageView];

}

- (void)updatePriceOrderImageView{
    if ([_order isEqualToString:@"priceAsc"]){
        _priceDescImageView.image = [UIImage imageNamed:@"lower_icon"];
    }else if ([_order isEqualToString:@"priceDesc"]){
        _priceDescImageView.image = [UIImage imageNamed:@"lower1_icon"];
    }else{
        _priceDescImageView.image = [UIImage imageNamed:@"lower2_icon"];
    }
}

- (void)updateOnSaleTimeOrderImageView{
    if ([_order isEqualToString:@"onsaleAsc"]){
        _onSaleDescImageView.image = [UIImage imageNamed:@"lower_icon"];
    }else if ([_order isEqualToString:@"onsaleDesc"]){
        _onSaleDescImageView.image = [UIImage imageNamed:@"lower1_icon"];
    }else{
        _onSaleDescImageView.image = [UIImage imageNamed:@"lower2_icon"];
    }
}

#pragma mark - EJSSegmentedControlDelegate
- (void)segmentedControl:(EJSSegmentedControl *)segmentedControl selectItemAtIndex:(NSUInteger)selectedIndex{
    if(_categoryModel){
        if(selectedIndex == 0){
            _categoryId = _categoryModel.categoryId;
        }else{
            EJSCategoryModel *model = self.categoryModel.sons[selectedIndex - 1];
            _categoryId = model.categoryId;
        }
    }
    if(_platformCategoryModel){
        if(selectedIndex == 0){
            _sortId = _platformCategoryModel.sortId;
            self.previousCategoryModel = _platformCategoryModel;
            self.previousCategoryModel.memorySroll = YES;
            self.canWriteIndex = NO;
        }else{
            XOPlatformCategoryModel *model = _platformCategoryModel.sons[selectedIndex - 1];
            _sortId = model.sortId;
            self.previousCategoryModel = model;
            self.previousCategoryModel.memorySroll = YES;
            self.canWriteIndex = NO;
        }
    }
    [self getGoodsList];
}
#pragma mark - Actions
- (IBAction)filterActin:(UIButton *)sender {
    _currentPage = 1;
    if(_currentSelectButton != sender){
        _currentSelectButton.selected = NO;
        sender.selected = YES;
        _currentSelectButton = sender;
        if (sender == self.defaultButton) {
            _order = nil;
        }else if (sender == self.salesButton){
            _order = @"";
        }
        else if (sender == self.priceButton){
            _order = @"priceAsc";
        }
        else if (sender == self.onSaleButton){
            _order = @"onsaleAsc";
        }
        [self updateOnSaleTimeOrderImageView];
        [self updatePriceOrderImageView];
        [self getGoodsList];
    }else{
        if (sender == self.priceButton){
            _order = [_order isEqualToString:@"priceAsc"]?@"priceDesc":@"priceAsc";
            [self updateOnSaleTimeOrderImageView];
            [self updatePriceOrderImageView];
            [self getGoodsList];
        }else if (sender == self.onSaleButton){
            _order = [_order isEqualToString:@"onsaleAsc"]?@"onsaleDesc":@"onsaleAsc";
            [self updateOnSaleTimeOrderImageView];
            [self updatePriceOrderImageView];
            [self getGoodsList];
        }
    }
}

#pragma mark - goosCellDelegate cell代理
- (BOOL)homeGoodCellIsLogin {
    return [self userIsLogin];
}

- (void)homeGoodUpdateShopCartWith:(XOShoppingCartModel *)cartListModel {
    self.shopCartModel = cartListModel;
}

- (void)homeGoodCellWillShowCartView:(XOShoppingCartModel *)cartModel andCurrentSpuId:(NSString *)spuId {
    NSMutableArray *tempArray = [NSMutableArray new];
    for (EJSShoppingCartGoodsModel *goodModel in cartModel.carts) {
        if ([goodModel.spuId isEqualToString: spuId]) {
            [tempArray addObject:goodModel];
        }
    }

    if (!(tempArray.count > 0)) {
        [[HUDHelper sharedInstance]tipMessage:@"本店铺暂无添加任何商品" delay:1.0];
        return;
    }

    [XOShopViewModel shared].shopCartGoodsList = tempArray;
    [XOShopViewModel shared].spuId = spuId;
    XOGoodsCartListView* cartView = [XOGoodsCartListView showSelectGoodsCartView: cartModel withCartList:_shoppingCartListModel];
    cartView.delegate = self;

}

#pragma mark - shopCartViewDelegate
- (void)shoppingCartViewWillDisapear {
    [self getCartList];
}

-(void)setShoppingCartListModel:(XOShoppingCartListModel *)shoppingCartListModel {
    _shoppingCartListModel = shoppingCartListModel;
    if (!(self.goodsList.count > 0)) {
        return;
    }
    EJSGoodsModel *goodModel = self.goodsList[0];
    EJSGoodsSkuModel *sku = goodModel.skus.firstObject;
    NSString *shopId = sku.shop_id == nil ? sku.shopId : sku.shop_id;
    [XOShopViewModel shared].shopId = shopId;
    for (XOShoppingCartModel *cart in _shoppingCartListModel.list) {
        if ([cart.shopId isEqualToString: shopId]) {
            self.shopCartModel = cart;
        }
    }
    [self.collectionView reloadData];
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{

    return self.goodsList.count;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    EJSHomeGoodCollectionViewCell *goodsCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"EJSHomeGoodCollectionViewCell" forIndexPath:indexPath];
    EJSGoodsModel *model = self.goodsList[indexPath.item];
    goodsCell.delegate = self;
    goodsCell.goodModel = model;
    goodsCell.shoppingCartListModel = self.shopCartModel;
    goodsCell.borderColor = UIColorFromRGB(0xE9E9E9);
    goodsCell.borderWidth = 0.5;
    goodsCell.delegate = self;
    return goodsCell;
}

- (void)shopCartGoodsCell:(EJSGoodsCCell *)cell addGoodsNum:(EJSGoodsModel *)model {
    [self getGoodsDetailInfo:model.spuId];

}

#pragma mark - Request
/// 获取商品列表
- (void)getGoodsList{
    BaseRequest *request = nil;
//    if(_keyWord){
//        EJSSearchGoodsRequest *req = [EJSSearchGoodsRequest new];
//        req.keyword = _keyWord;
//        req.order = _order;
//        req.page = @(_currentPage).stringValue;
//        req.pageLimit = @"100";
//        req.shopId = _shopId;
//        request = req;
//    }else{
//        EJSGoodsListRequest *req = [EJSGoodsListRequest new];
//        req.categoryId = _categoryId;
//        req.order = _order;
//        req.page = @(_currentPage).stringValue;
//        req.pageLimit = @"100";
//        req.labelId = nil;
//        req.sortId = _sortId;
//        req.shopId = _shopId;
//        request = req;
//    }
    EJSGoodsListRequest *req = [EJSGoodsListRequest new];
    req.keyword = _keyWord;
    req.shopId = _shopId;
    req.categoryId = _categoryId;
    req.order = _order;
    req.page = @(_currentPage).stringValue;
    req.pageLimit = @"100";
    req.labelId = nil;
    req.sortId = _sortId;
    request = req;


    FlyWeakSelf
    [request asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        [weakSelf.collectionView.mj_header endRefreshing];
        [weakSelf.collectionView.mj_footer endRefreshing];

        EJSGoodsListModel *listModel = response.data;
        if(listModel){
            if(listModel.totalPages.integerValue == listModel.page.integerValue){
                [weakSelf.collectionView.mj_footer endRefreshingWithNoMoreData];
            }
            if(_currentPage == 1){
                weakSelf.goodsList = [NSMutableArray arrayWithArray:listModel.list];
            }else{
                [weakSelf.goodsList addObjectsFromArray:listModel.list];
            }
        }
        if(self.goodsList.count > 0){
            [self hideNoDataView];
        }else{
            [self showNoDataViewWithText:@"暂无商品数据"];
        }
        [weakSelf.collectionView reloadData];
        [weakSelf getCartList];
    } failHandler:^(BaseResponse *response) {
        [weakSelf.collectionView.mj_header endRefreshing];
        [weakSelf.collectionView.mj_footer endRefreshing];
        [[HUDHelper sharedInstance] tipMessage:response.message];
    }];
}

/// 获取购物车列表
- (void)getCartList{
    FlyWeakSelf
    [[XOShopCartViewModel shared] updateCartList:^(XOShoppingCartListModel * _Nonnull response) {
        if (response) {
            weakSelf.shoppingCartListModel = response;
        }else {
            [weakSelf.collectionView reloadData];
        }
        if (!(weakSelf.goodsList.count > 0)) {
            return;
        }
        if (_hasPlatform) {
            if (weakSelf.previousCategoryModel.previouIndex && weakSelf.previousCategoryModel.memorySroll) {
                [weakSelf.collectionView scrollToItemAtIndexPath:weakSelf.previousCategoryModel.previouIndex atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
            }else if (!weakSelf.previousCategoryModel.previouIndex){
                [weakSelf.collectionView scrollToItemAtIndexPath: [NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
            }
            weakSelf.canWriteIndex = YES;
        }
    }];
}


    //MARK:- 添加到购物车 (先获取详情)
- (void)getGoodsDetailInfo:(NSString *)goodId{
    EJSGoodsDetailInfoRequest *req = [EJSGoodsDetailInfoRequest new];
    req.spuId = goodId;
    FlyWeakSelf;
    [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        [weakSelf addToShoppingCartAction:response.data];
    } failHandler:^(BaseResponse *response) {
        [[HUDHelper sharedInstance] tipMessage:response.message];
    }];
}

- (void)addToShoppingCartAction:(EJSGoodsModel *)detaiModel {
    if([self userIsLogin]){
        if(detaiModel.hasDefaultSku.integerValue == 1 && detaiModel.skus.count > 0){
            self.selectSkuModel = detaiModel.skus.firstObject;
            self.selectSkuModel.skuSelectCount = detaiModel.minToBuy.integerValue;
            [self addToCartReq:self.selectSkuModel];
            return;
        }
        FlyWeakSelf
        [EJSSelectGoodsSpecView showSelectGoodsSpecView:detaiModel completion:^(EJSGoodsSkuModel *selectSkuModel) {
            [weakSelf addToCartReq:selectSkuModel];
        }];
    }
}

- (void)addToCartReq:(EJSGoodsSkuModel *)skuModel{
    EJSGoodsAddCartRequest *req = [EJSGoodsAddCartRequest new];
    req.skuId = skuModel.skuId;
    req.num = @(skuModel.skuSelectCount).stringValue;
    FlyWeakSelf
    [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        [[HUDHelper sharedInstance] tipMessage:@"加入购物车成功"];
        if(weakSelf.selectSkuModel){
            weakSelf.selectSkuModel = nil;
        }
    } failHandler:^(BaseResponse *response) {
        [[HUDHelper sharedInstance] tipMessage:response.message];
    }];
}

#pragma mark - UICollectionViewDelegateFlowLayout

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 0, 0, 0);;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 0;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat width = (ScreenWidth - 0)/2;
    CGFloat height = 170 + ScreenWidth/2.0 * (300/375.0);
    return CGSizeMake(width, height);
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    EJSGoodsDetailInfoViewController *goodsDetailVC = [[EJSGoodsDetailInfoViewController alloc] initWithNibName:@"EJSGoodsDetailInfoViewController" bundle:nil];
    EJSGoodsModel *goodModel = self.goodsList[indexPath.row];
    goodsDetailVC.goodsId = goodModel.spuId;
//    EJSGoodsSkuModel *skuModel = goodModel.skus.firstObject;
//    [goodsDetailVC setDatasWith:self.goodsList and:skuModel.shopId and:indexPath andCurrentGoodModel:goodModel];
//    goodsDetailVC.delegate = self;
    [self.navigationController pushViewController:goodsDetailVC animated:YES];
}

- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    if (_canWriteIndex) {
        NSIndexPath *index = [collectionView indexPathForCell:collectionView.visibleCells.firstObject];
        self.previousCategoryModel.previouIndex = index;
    }

}

#pragma mark - 详情页代理
- (void)goodsDetailWillDisappearWithIndex:(NSIndexPath *)indexPath {
    self.previousCategoryModel.memorySroll = NO;
    [self getCartList];
    [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
}
@end
